package com.lmt.controller;

import com.lmt.common.entity.ErrorCode;
import com.lmt.common.entity.Result;
import com.lmt.common.util.ResultUtil;
import com.lmt.entity.UserInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class Controller {

    @RequestMapping("/signIn")
    public Result login(@RequestBody(required = false) UserInfo userInfo) {
        if (ObjectUtils.isEmpty(userInfo)) {
            return ResultUtil.failure(ErrorCode.LOGIN_AGAIN);
        }
        Subject currentUser = SecurityUtils.getSubject();
        if (!currentUser.isAuthenticated()) {
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken();
            usernamePasswordToken.setUsername(userInfo.getUsername());
            usernamePasswordToken.setPassword(userInfo.getPassword().toCharArray());
            SecurityManager securityManager = SecurityUtils.getSecurityManager();
            try {
                currentUser.login(usernamePasswordToken);
            } catch (AuthenticationException exception) {
                return ResultUtil.failure(ErrorCode.LOGIN_FAILURE);
            }
        }
        return ResultUtil.success();
    }

    @RequestMapping("/unauthorized")
    public Result unauthorized() {
        return ResultUtil.failure(ErrorCode.NO_PERMISSIONS);
    }

}
